/**
 * 
 */

package com.kugou.game.sdk.ui.fragment;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseSDKWorkerFragment;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.AccountSecurityInfo;
import com.kugou.game.sdk.interfaces.OnRequestListener;
import com.kugou.game.sdk.interfaces.onAccountSecurityInfoListener;
import com.kugou.game.sdk.persistence.preference.PrefUtil;
import com.kugou.game.sdk.ui.activity.BindSecurityEmailActivity;
import com.kugou.game.sdk.ui.activity.CommonSdkActivity;
import com.kugou.game.sdk.ui.activity.ModifyPasswordActivity;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.dialog.SetPayPsdSuccessDialog;
import com.kugou.game.sdk.ui.widget.TipsLayout;
import com.kugou.game.sdk.ui.widget.UserInfoView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * 描述:用户安全页面
 *
 * @author jerryliu
 * @since 2015年8月17日 上午11:37:01
 */
public class AccountSecurityFragment extends BaseSDKWorkerFragment {

    private static final int MSG_BACK_LOAD_ACCOUNT_SECURITY = 0;

    private static final int MSG_UI_LOAD_ACCOUNT_SECURITY_SUCCESS = 1;

    private static final int MSG_UI_LOAD_ACCOUNT_SECURITY_FAILE = 2;

    private static final int MSG_UI_START_LOADING = 3;

    private static final int MSG_BACK_REQUEST_SEND_MODIFY_SECURITY_EMAIL_CODE = 4;

    private static final int MSG_UI_REQUEST_SEND_MODIFY_SECURITY_EMAIL_CODE_SUCCESS = 5;

    private static final int MSG_UI_REQUEST_SEND_MODIFY_SECURITY_EMAIL_CODE_FAILE = 6;

    private UserInfoView mSecurityPhoneView, mSecurityEmailView, mSecurityQuestionView,
            mSecurityModifyPsdView, mSecurityPayPsdView;

    private TextView mAccount, mSecurityText, mSecurityScore;

    private ImageView mImage1, mImage2, mImage3, mImage4;

    private Activity context;

    private TipsLayout mTipsLayout;

    private View mLayoutContent;

    private User user;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        user = UserManager.getInstance().getCurrentUserInternal();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = null;
        int orientation = SDKControler.getActivityOrientation();
        if (orientation == ActivityOrientation.PORTRAIT) {
            view = inflater.inflate(Rx.layout.kg_fragment_account_security_portrait, null);
        } else {
            view = inflater.inflate(Rx.layout.kg_fragment_account_security_land, null);
        }
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        sendEmptyBackgroundMessage(MSG_BACK_LOAD_ACCOUNT_SECURITY);
    }

    private void initView(View view) {
        mTipsLayout = (TipsLayout) view.findViewById(Rx.id.kg_loading);
        mTipsLayout.setOnRefreshButtonClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                sendEmptyBackgroundMessage(MSG_BACK_LOAD_ACCOUNT_SECURITY);
            }
        });
        mLayoutContent = view.findViewById(Rx.id.kg_layout_bind_phone);
        mAccount = (TextView) view.findViewById(Rx.id.kg_security_account);
        mAccount.setText(Html.fromHtml("账号：" + "<font color=\"#666666\">" + user.getAccountName()
                + "</font>"));

        mSecurityText = (TextView) view.findViewById(Rx.id.kg_security_score_text);
        mSecurityScore = (TextView) view.findViewById(Rx.id.kg_security_score_num);
        mImage1 = (ImageView) view.findViewById(Rx.id.kg_security_img_1);
        mImage2 = (ImageView) view.findViewById(Rx.id.kg_security_img_2);
        mImage3 = (ImageView) view.findViewById(Rx.id.kg_security_img_3);
        mImage4 = (ImageView) view.findViewById(Rx.id.kg_security_img_4);

        mSecurityPhoneView = (UserInfoView) view.findViewById(Rx.id.kg_item_security_phone);
        mSecurityPhoneView.setOnBtnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (TextUtils.isEmpty(user.getBindPhoneNum())) {
                    context.startActivity(CommonSdkActivity.creatIntent(context,
                            BindPhoneFragment.class.getName(),
                            Rx.string.kg_kugou_security_phone_title));
                } else {
                    context.startActivity(CommonSdkActivity.creatIntent(context,
                            UpdateBindPhoneFragment.class.getName(),
                            Rx.string.kg_kugou_security_phone_title));
                }
            }
        });

        mSecurityEmailView = (UserInfoView) view.findViewById(Rx.id.kg_item_security_email);
        mSecurityEmailView.setOnBtnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String loginEmail = user.getLoginEmail();
                String securityEmail = user.getSecurityEmail();
                if (!TextUtils.isEmpty(securityEmail) && !TextUtils.isEmpty(loginEmail)
                        && securityEmail.equalsIgnoreCase(loginEmail)) {
                    if (dialog == null) {
                        dialog = new ProgressDialog(context);
                        dialog.setMessage("正在操作，请稍候...");
                    }

                    if (getActivity() != null && !getActivity().isFinishing()) {
                        dialog.show();
                    }
                    sendEmptyBackgroundMessage(MSG_BACK_REQUEST_SEND_MODIFY_SECURITY_EMAIL_CODE);
                } else {
                    context.startActivity(new Intent(context, BindSecurityEmailActivity.class));
                }
            }
        });

        mSecurityQuestionView = (UserInfoView) view.findViewById(Rx.id.kg_item_security_question);
        mSecurityQuestionView.setOnBtnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (user.getSecurityQuestionId() != 255) {
                    showToast("安全问题已设置，暂时不提供修改");
                } else {
                    context.startActivity(CommonSdkActivity.creatIntent(context,
                            SetSecurityQuestionFragment.class.getName(),
                            Rx.string.kg_set_security_quesition));
                }
            }
        });

        mSecurityModifyPsdView = (UserInfoView) view.findViewById(Rx.id.kg_item_modify_psd);
        mSecurityModifyPsdView.setBtnText("修改");
        mSecurityModifyPsdView.setOnBtnClickListener(new OnClickListener() {
            public void onClick(View v) {
                context.startActivity(new Intent(context, ModifyPasswordActivity.class));
            }
        });

        mSecurityPayPsdView = (UserInfoView) view.findViewById(Rx.id.kg_item_pay_psd);
        mSecurityPayPsdView.setOnBtnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (user.getPayPsd() == 1) {
                    context.startActivity(CommonSdkActivity.creatIntent(context,
                            SecurityPsdModifyFragment.class.getName(),
                            Rx.string.kg_update_security_psd));
                } else {
                    context.startActivity(CommonSdkActivity.creatIntent(context,
                            SecurityPsdSetFragment.class.getName(), Rx.string.kg_set_security_psd));
                }
            }
        });
    }

    ProgressDialog dialog;

    @Override
    public void setupActions(ArrayList<String> actions) {
        super.setupActions(actions);
        actions.add(SDKActions.ACTION_UPDATE_BIND_SECURITY_EMAIL_SUCCESS);
        actions.add(SDKActions.ACTION_UPDATE_BIND_PHONE_SUCCESS);
        actions.add(SDKActions.ACTION_SET_SECURITY_QUESTION_SUCCESS);
        actions.add(SDKActions.ACTION_SET_PAY_PSD_SUCCESS);
    }

    @Override
    public void handleBroadcast(Context context, Intent intent) {
        super.handleBroadcast(context, intent);
        String action = intent.getAction();
        if (action.equals(SDKActions.ACTION_UPDATE_BIND_SECURITY_EMAIL_SUCCESS)) {
            refreshSecurityEmail();
        } else if (action.equals(SDKActions.ACTION_UPDATE_BIND_PHONE_SUCCESS)) {
            refreshSecurityPhone();
        } else if (action.equals(SDKActions.ACTION_SET_SECURITY_QUESTION_SUCCESS)) {
            refreshSecurityQuestion();
        } else if (action.equals(SDKActions.ACTION_SET_PAY_PSD_SUCCESS)) {
            refreshSecurityPayPsd();
            showSetPayPsdSuccessDialog();
        }
        refreshSecurityScore();
    }

    private void showSetPayPsdSuccessDialog() {
        if (user.getSecurityScore() == 100) {
            final BaseConfirmDialog dialog = new BaseConfirmDialog(context);
            dialog.setMessage("支付密码设置成功");
            dialog.setSuccessLogoVisibility(View.VISIBLE);
            dialog.setDialogTitle("提示");
            dialog.setCancelBtnVisibility(View.GONE);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setOKBtnText("知道了");
            dialog.setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
            dialog.setCancelable(false);
            dialog.setOKClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        } else {
            boolean showInSp = PrefUtil.getPaySecurityTipNeedShow(getActivity(), user.getOpenId());
            if (showInSp) {
                boolean showInSDcard = PayManager.getPaySecurityTipNeedShow(user.getOpenId());
                if (showInSDcard) {
                    SetPayPsdSuccessDialog dialoga = new SetPayPsdSuccessDialog(getActivity());
                    dialoga.setWindowSize(0.9, 0.75);
                    dialoga.setCloseImgVisibility(false);
                    dialoga.setOkBtnVisible(false);
                    dialoga.setTitle("提示");
                    dialoga.setCancelBtnText("立即设置");
                    dialoga.show();
                } else {
                    PrefUtil.setPaySecurityTipNeedShow(getActivity(), user.getOpenId(), false);
                }
            }
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        final Message message = new Message();
        String username = user.getAccountName();
        String kgToken = user.getKugouToken();
        String email = user.getSecurityEmail();
        switch (msg.what) {
            case MSG_BACK_LOAD_ACCOUNT_SECURITY:
                sendEmptyUiMessage(MSG_UI_START_LOADING);
                UserManager.getInstance().requestAccountSecurityInfo(
                        new onAccountSecurityInfoListener() {
                            @Override
                            public void onSuccess(AccountSecurityInfo info) {
                                message.what = MSG_UI_LOAD_ACCOUNT_SECURITY_SUCCESS;
                                message.obj = info;
                            }

                            @Override
                            public void onFaile(String errorMsg) {
                                message.what = MSG_UI_LOAD_ACCOUNT_SECURITY_FAILE;
                                message.obj = errorMsg;
                            }
                        });
                break;
            case MSG_BACK_REQUEST_SEND_MODIFY_SECURITY_EMAIL_CODE:
                UserManager.getInstance().sendSecurityEmailCode(username, kgToken, email, 2,
                        new OnRequestListener() {
                            @Override
                            public void onSuccess() {
                                message.what = MSG_UI_REQUEST_SEND_MODIFY_SECURITY_EMAIL_CODE_SUCCESS;
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                message.what = MSG_UI_REQUEST_SEND_MODIFY_SECURITY_EMAIL_CODE_FAILE;
                                message.obj = errorMsg;
                            }
                        });
                break;
        }
        sendUiMessage(message);
    }

    @Override
    public void handleUiMessage(Message msg) {
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }

        switch (msg.what) {
            case MSG_UI_START_LOADING:
                mTipsLayout.show(TipsLayout.TYPE_LOADING);
                mLayoutContent.setVisibility(View.GONE);
                break;
            case MSG_UI_LOAD_ACCOUNT_SECURITY_SUCCESS:
                mTipsLayout.hide();
                mLayoutContent.setVisibility(View.VISIBLE);
                refreshPage();
                break;
            case MSG_UI_LOAD_ACCOUNT_SECURITY_FAILE:
                mTipsLayout.show(TipsLayout.TYPE_FAILE);
                mLayoutContent.setVisibility(View.GONE);
                break;
            case MSG_UI_REQUEST_SEND_MODIFY_SECURITY_EMAIL_CODE_SUCCESS:
                if (dialog != null) {
                    dialog.dismiss();
                }
                Intent intent = new Intent(context, BindSecurityEmailActivity.class);
                intent.putExtra(BindSecurityEmailActivity.SHOW_BIND_SECURITY_EMAIL_RESULT, true);
                context.startActivity(intent);
                break;
            case MSG_UI_REQUEST_SEND_MODIFY_SECURITY_EMAIL_CODE_FAILE:
                if (dialog != null) {
                    dialog.dismiss();
                }

                if (msg.obj != null) {
                    showToast(msg.obj.toString());
                }
                break;
        }
    }

    private void refreshPage() {
        // 安全评分
        refreshSecurityScore();

        // 安全手机
        refreshSecurityPhone();

        // 安全邮箱
        refreshSecurityEmail();

        // 支付密码
        refreshSecurityPayPsd();

        // 安全问题
        refreshSecurityQuestion();
    }

    private void refreshSecurityQuestion() {
        if (user.getSecurityQuestionId() != 255) {
            mSecurityQuestionView.setBtnText("已设置");
        } else {
            mSecurityQuestionView.setBtnText("立即设置");
        }
    }

    private void refreshSecurityPayPsd() {
        if (user.getPayPsd() == 1) {
            mSecurityPayPsdView.setBtnText("修改");
        } else {
            mSecurityPayPsdView.setBtnText("立即设置");
        }
    }

    private void refreshSecurityEmail() {
        if (TextUtils.isEmpty(user.getSecurityEmail())) {
            mSecurityEmailView.setBtnText("立即设置");
        } else {
            mSecurityEmailView.setBtnText("修改");
            mSecurityEmailView.setSubTitleText(AppUtil.getEmailWithStar(user.getSecurityEmail()));
        }
    }

    private void refreshSecurityScore() {
        // 安全图标
        if (!TextUtils.isEmpty(user.getBindPhoneNum())) {
            mImage1.setImageResource(Rx.drawable.kg_security_phone_binded);
        } else {
            mImage1.setImageResource(Rx.drawable.kg_security_phone_default_gray);
        }
        if (!TextUtils.isEmpty(user.getSecurityEmail())) {
            mImage2.setImageResource(Rx.drawable.kg_security_email_binded);
        } else {
            mImage2.setImageResource(Rx.drawable.kg_security_email_default_gray);
        }
        if (user.getSecurityQuestionId() != 255) {
            mImage3.setImageResource(Rx.drawable.kg_security_question_set);
        } else {
            mImage3.setImageResource(Rx.drawable.kg_security_question_default_gray);
        }
        if (user.isSetIdentity()) {
            mImage4.setImageResource(Rx.drawable.kg_security_identity_binded);
        } else {
            mImage4.setImageResource(Rx.drawable.kg_security_identity_default_gray);
        }

        // 安全评分
        mSecurityScore.setText(String.valueOf(user.getSecurityScore()));
        if (user.getSecurityScore() == 100) {
            mSecurityText.setTextColor(getResources().getColor(Rx.color.kg_common_green_light));
            mSecurityScore.setTextColor(getResources().getColor(Rx.color.kg_common_green_light));
            mSecurityScore.setBackgroundResource(Rx.drawable.kg_circle_bg_green);
        } else {
            mSecurityText.setTextColor(getResources().getColor(Rx.color.kg_common_red));
            mSecurityScore.setTextColor(getResources().getColor(Rx.color.kg_common_red));
            mSecurityScore.setBackgroundResource(Rx.drawable.kg_circle_bg_red);
        }
    }

    private void refreshSecurityPhone() {
        if (TextUtils.isEmpty(user.getBindPhoneNum())) {
            mSecurityPhoneView.setBtnText("立即绑定");
        } else {
            mSecurityPhoneView.setBtnText("修改");
            mSecurityPhoneView.setSubTitleText(AppUtil.getPhoneWithStar(user.getBindPhoneNum()));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }
}
